//
//  SYDMessageViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/14.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDMessageViewController.h"
#import "SYDMessageCell.h"
#import "SYDMessageModel.h"

static NSString *messageId = @"SYDMessageCell";
@interface SYDMessageViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataList;
@property (weak, nonatomic) IBOutlet UIView *noDataView;

@property (nonatomic, strong) YMNodataView * noNetView;
@end

@implementation SYDMessageViewController
#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
//    [weakSelf rightNavButtonWithTitle:@"清空" action:^{
//        NSLog(@"点击了清空数据源");
//        
//        [self.dataList removeAllObjects];
//        [self.tableView removeFromSuperview];
//        self.noDataView.hidden = NO;
//    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
     self.navigationBar.title = @"车秘书";
    [self navigationBarHandle];
    [self initMessageUI];
    self.noNetView.userInteractionEnabled = YES;
    [self.noNetView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(getMessageFromServer)]];
    [self.view bringSubviewToFront:self.noDataView];
}

-(void)initMessageUI{
    if (@available(iOS 11.0,*)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:messageId bundle:nil] forCellReuseIdentifier:messageId];
    
    //WEAKSELF
    [SYDHasNetWork syd_hasNetwork:^(bool has) {
        if (has) {
            NSLog(@"有网络");
        }else{
            NSLog(@"无网络");
        }
    }];
    if(![SYDHasNetWork connectedToNetwork])
    {
        [self showNoNetView];
        [self.tableView reloadData];
        
    }else{
     [self getMessageFromServer];
    }
}
-(void)getMessageFromServer{
    WEAKSELF
    [[SYDNetwork shareTool]GetHomePageMsgWithCityCode:[YMSaveTool valueForKey:CityCode] success:^(NSURLSessionDataTask *task, id responseObject) {
        @try {
            if ([responseObject[@"statusCode"]integerValue] == 200) {
                [weakSelf hideNoNetView];
                //NSLog(@"%@",responseObject);
                if (weakSelf.dataList.count > 0) {
                    [weakSelf.dataList removeAllObjects];
                    
                }
                self.dataList = [SYDMessageModel mj_objectArrayWithKeyValuesArray:responseObject[@"obj"]];
            }else{
                [SVProgressHUD displayInfoWithStatus:responseObject[@"msg"]];
            }
        } @catch (NSException *exception) {
            NSLog(@"----%@",exception.description);
        } @finally {
            
        }
        if (weakSelf.dataList.count > 0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }else{
            [weakSelf.tableView removeFromSuperview];
            weakSelf.noDataView.hidden = NO;
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}
#pragma mark---UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataList.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SYDMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:messageId];
    SYDMessageModel *model = self.dataList[indexPath.section];
    [cell fullMessageWith:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//返回cell的的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SYDMessageModel *model = self.dataList[indexPath.section];
   
    return [self heightForRowWithContent:model.content];
    
}
//动态计算cell的高度
- (CGFloat)heightForRowWithContent:(NSString *)content
{
    //这里只写了label的计算
    //文本的高度
    CGSize texSize = [self labelAutoCalculateRectWith:content FontSize:14 MaxSize:CGSizeMake(SCREEN_WIDTH - 60,MAXFLOAT)];
    //3.返回cell 的总高度
    return 95 + texSize.height;
}
/*根据传过来的文字内容、字体大小、宽度和最大尺寸动态计算文字所占用的size
 * text 文本内容
 * fontSize 字体大小
 * maxSize  size（宽度，1000）
 * return  size （计算的size）
 */
- (CGSize)labelAutoCalculateRectWith:(NSString*)text FontSize:(CGFloat)fontSize MaxSize:(CGSize)maxSize
{
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;
    NSDictionary* attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGSize labelSize;
    //如果是IOS6.0
    if (![text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
        labelSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    }else{//如果系统为iOS7.0
        
        // iOS7中用以下方法替代过时的iOS6中的sizeWithFont:constrainedToSize:lineBreakMode:方法
        labelSize = [text boundingRectWithSize: maxSize options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine attributes:attributes context:nil].size;
    }
    labelSize.height= ceil(labelSize.height);
    labelSize.width= ceil(labelSize.width);
    return labelSize;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    SYDMessageModel *model = self.dataList[section];
    static NSString * identy = @"messageHeader";
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    if (!hf) {
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        CGFloat height;
        CGFloat labelY;
        if (section == 0) {
            height = 47.5;
            labelY = 20;
        }else{
            height = 40;
            labelY = 12.5;
        }
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0,0, SCREEN_WIDTH,height)];
        view.backgroundColor = CONTENT_BG_COLOR;
        [hf addSubview:view];
        
        NSString * time = [NSString timestamp2MonthMinute:model.gmtCreate];
        CGFloat width = [NSString boundingRectWithString:time font:[UIFont systemFontOfSize:14]].width + 10;

        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(view.centerX - 55, labelY, width, 20)];
        label.text = time;
        label.textColor = WHITE_COLOR;
        label.backgroundColor  = [UIColor colorWithHexString:@"#acb0b4"];
        label.layer.cornerRadius = 3;
        label.layer.borderWidth = 1;
        label.layer.masksToBounds  = YES;
        label.layer.borderColor  = [UIColor colorWithHexString:@"#acb0b4"].CGColor;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:14];
        [view addSubview:label];
    }
    return hf;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
// tableView 如果是Gruop类型的话，section之间的间距变宽，执行返回高度的同时还需要执行return UIView的代理
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 47.5;
    }
    return 40;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

#pragma mark - Lazy
-(UITableView *)tableView{
    
    if (_tableView == nil) {
        if (iPhone8_X) {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 88, SCREEN_WIDTH, SCREEN_HEIGHT - 88) style:UITableViewStyleGrouped];
        } else {
            _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) style:UITableViewStyleGrouped];
        }
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = CONTENT_BG_COLOR;
        _tableView.tipsStr = @"暂无消息记录！";
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(NSMutableArray *)dataList{
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

//无网络,连接失败
- (YMNodataView *)noNetView{
    if (!_noNetView) {
        
        _noNetView = [[YMNodataView alloc]initWithFrame:CGRectMake(0, STATUS_AND_NAVIGATION_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_AND_NAVIGATION_HEIGHT) image:[UIImage imageNamed:@"icon_withdrawal"] imageWidth:132 title:@"网络连接失败,请查看网络是否连接正常！"];
    }
    return _noNetView;
}

- (void)showNoNetView{
    
    self.tableView.tableFooterView = self.noNetView;
}

- (void)hideNoNetView{
    self.tableView.tableFooterView = nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


















































